package org.csu.linkgame.controller;

import com.leewyatt.rxcontrols.controls.RXTranslationButton;
import com.leewyatt.rxcontrols.event.RXActionEvent;
import de.felixroske.jfxsupport.FXMLController;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.image.Image;
import javafx.stage.Modality;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import org.csu.linkgame.LinkGameApplication;
import org.csu.linkgame.domain.User;
import org.csu.linkgame.service.ClassForDoubleGame.SocketThread2;
import org.csu.linkgame.service.ClassForDoubleGame.dgServiceImpl;
import org.csu.linkgame.service.ClassForDoubleGame.dgUtils;
import org.csu.linkgame.service.ClassForGame.Utils;
import org.csu.linkgame.service.UserService;
import org.csu.linkgame.utils.AlertView;
import org.csu.linkgame.utils.ServiceUtil;
import org.csu.linkgame.utils.WSClient;
import org.csu.linkgame.utils.WSStorage;
import org.csu.linkgame.view.AdminView;
import org.csu.linkgame.view.RegisterView;
import org.pan.decorate.StageDecorate;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.*;
import java.net.Socket;
import java.net.URL;
import java.util.List;
import java.util.Properties;
import java.util.ResourceBundle;

@FXMLController
public class LoginViewController implements Initializable {

    @FXML
    private TextField userNameTextField;
    @FXML
    private PasswordField passwordTextField;
    @FXML
    private CheckBox rememberCheck;
    @FXML
    private RXTranslationButton loginButton;
    @FXML
    private RXTranslationButton registerButton;
    dgServiceImpl dgCanvas;
    @Override
    public void initialize(URL location, ResourceBundle resources) {
        //读取user_info.properties中的数据
        Properties prop = new Properties();
        try {
            if (new File("user_info.properties").exists()) {
                InputStream in = new BufferedInputStream(new FileInputStream("user_info.properties"));
                prop.load(in);
                for (String key : prop.stringPropertyNames()) {
                    if(prop.getProperty("isRemember").equals("1")){
                        userNameTextField.setText(prop.getProperty("username"));
                        passwordTextField.setText(prop.getProperty("password"));
                        rememberCheck.setSelected(true);
                    }else {
                        userNameTextField.setText(prop.getProperty("username")); // 实现仅自动记住上使用过的账号
                        passwordTextField.setText("");
                        rememberCheck.setSelected(false);
                    }
                }
                in.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        dgUtils dgu = new dgUtils(2);
        Utils ut = new Utils(2);
    }

    /**
     * 登录按钮
     * @param event
     * @throws IOException
     */
    public void handleSubmitButtonAction(ActionEvent event) throws IOException {
        AlertView alertView = new AlertView(Alert.AlertType.NONE);
        String username = userNameTextField.getText();
        String password = passwordTextField.getText();
        if (username.equals("")) {
            System.out.println("请填写用户名!");
            alertView.showAlert(Alert.AlertType.WARNING, "警告", "请填写用户名!", ButtonType.OK);
        } else if (password.equals("")) {
            System.out.println("请填写密码!");
            alertView.showAlert(Alert.AlertType.WARNING, "警告", "请填写密码!", ButtonType.OK);
        } else {
            int i = ServiceUtil.serviceUtil.userService.checkLogin(username, password);
            if (i == 0) {
                // 登录失败，用户名不存在！
                userNameTextField.setText("");
                passwordTextField.setText("");
                alertView.showAlert(Alert.AlertType.ERROR, "错误", "用户名不存在！！！", ButtonType.OK);
            } else if (i == 1) {
                // 登录验证成功
                alertView.showAlert(Alert.AlertType.INFORMATION, "提示", "登录成功！！！", ButtonType.OK);
                if (rememberCheck.isSelected()) {
                    rememberUserInformation(username, password);
                } else {
                    forgetUserInformation(username, password);
                }
                // 客户端上线
//                WSClient.setLoginUser(username);
//                WSStorage.getInstance().setLoginUser(username);//存储当前用户名
//                WSClient.getInstance().connect();
                // 获取当前窗口
                Stage loginStage = (Stage) loginButton.getScene().getWindow();
                // 关闭窗口
                loginStage.close();
                // 打开主界面
                User user = ServiceUtil.serviceUtil.userService.getUserInfoByUsername(username);
                if (user.getIsAdmin() == 0) {
                    try{
                        // 客户端连接线程,监听服务端的数据的代码在下面
                        Socket socket = new Socket("127.0.0.1", 9999);
                        System.out.println("恭喜你与服务器连接成功!");
                        // 获取服务端的游戏数据
                        ObjectInputStream is = null;
                        is = new ObjectInputStream(new BufferedInputStream(socket.getInputStream()));
                        Object obj = is.readObject();
                        List<Integer> randomRowList = (List<Integer>)obj;

                        Object obj2 = is.readObject();
                        List<Integer> randomColList = (List<Integer>)obj2;
                        System.out.println("我已接受Row列表:"+randomRowList);
                        System.out.println("我已接受Col列表:"+randomColList);
                        dgServiceImpl dgCanvas = new dgServiceImpl(randomRowList,randomColList,socket);
                        this.dgCanvas = dgCanvas;
                        // 新开线程监听服务端发来的数据
                        new Thread(new SocketThread2(socket,dgCanvas,user)).start();

                    }catch (Exception e){
                        e.printStackTrace();
                    }
                    sendUserInfoAndSkipToMainView(user,dgCanvas);
                    ServiceUtil.serviceUtil.logService.insertLog(user.getUsername() + "登录了系统");
                } else {
                    sendUserInfoAndSkipToAdminView(user);
                    ServiceUtil.serviceUtil.logService.insertLog(user.getUsername() + "登录了后台");
                }
            } else {
                // 登录失败，密码错误
                passwordTextField.setText("");
                alertView.showAlert(Alert.AlertType.ERROR, "错误", "密码错误！！！", ButtonType.OK);
            }
        }
    }

    /**
     * 注册按钮
     * @param event
     * @throws IOException
     */
    public void handleRegisterButtonAction(ActionEvent event) throws IOException {
//        LinkGameApplication.showView(RegisterView.class, Modality.NONE);
        FXMLLoader loader = new FXMLLoader(getClass().getResource("../view/register.fxml"));
        Parent root = loader.load();
        Stage stage = new Stage(StageStyle.DECORATED);
        stage.setScene(new Scene(root));
        StageDecorate.decorate(stage,root);

        stage.setTitle("新用户注册界面");
        stage.getIcons().add(new Image("/org/csu/linkgame/images/icon.png"));

        stage.show();
    }

    // 勾选记住密码
    private void rememberUserInformation(String username, String password) {
        Properties properties = new Properties();
        try {
            System.out.println("记住密码");
            FileOutputStream oFile = new FileOutputStream("user_info.properties", false); //这里true表示追加,false会将原文件清空后,重新添加.
            properties.setProperty("username", username);
            properties.setProperty("password", password);
            properties.setProperty("isRemember", "1");//用以判断是否输出用户名密码
            properties.store(oFile, null);
            oFile.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 不勾选记住密码
    private void forgetUserInformation(String username, String password) {
        Properties properties = new Properties();
        try {
            System.out.println("取消记住密码");
            FileOutputStream oFile = new FileOutputStream("user_info.properties", false);
            properties.setProperty("username", username);
            properties.setProperty("password", password);
            properties.setProperty("isRemember", "0");// 修改为0
            properties.store(oFile, null);
            oFile.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void sendUserInfoAndSkipToMainView(User user,dgServiceImpl dgCanvas) throws IOException {
//        FXMLLoader loader = new FXMLLoader(getClass().getResource("../view/main.fxml"));
//        Stage stage = new Stage(StageStyle.DECORATED);
//        stage.setScene(new Scene(loader.load()));
//
//        MainViewController mainViewController = loader.getController();
//        mainViewController.setUser(user);
//
//        stage.show();

        FXMLLoader loader = new FXMLLoader(getClass().getResource("../view/text.fxml"));
        Parent root = loader.load();
//        Parent root = FXMLLoader.load(LinkGameApplication.class.getResource("./view/text.fxml"));
        Stage stage = new Stage(StageStyle.DECORATED);
        stage.setScene(new Scene(root));
        StageDecorate.decorate(stage,root);
        stage.setTitle("超级连连看٩( 'ω' )و ");
        stage.getIcons().add(new Image("/org/csu/linkgame/images/icon.png"));

        TextController textController = loader.getController();
        textController.setUser(user);

        textController.setDgCanvas(dgCanvas);

        stage.show();
    }

    private void sendUserInfoAndSkipToAdminView(User user) throws IOException {
        FXMLLoader loader = new FXMLLoader(getClass().getResource("../view/admin.fxml"));
        Parent root = loader.load();
        Stage stage = new Stage(StageStyle.DECORATED);
        stage.setScene(new Scene(root));
        StageDecorate.decorate(stage, root);
        stage.setTitle("超&连系统后台管理界面");
        stage.getIcons().add(new Image("/org/csu/linkgame/images/icon.png"));
        AdminViewController adminViewController = loader.getController();
        adminViewController.setUser(user);

        stage.show();
    }

    public void deleteText(RXActionEvent rxActionEvent) {
        userNameTextField.setText("");
    }
}
